/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller.SEC;

import business.SEC.SecLoginBusiness;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.EJB;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import util.Constant.Constant;
import util.Constant.ConstantjQueryDialogState;
import util.jQueryForm.Dialog.jQueryFormDialog;
import util.jQueryForm.Dialog.jQueryFormDialogOption;
import util.jQueryForm.jQueryFormFormatterUtil;

/**
 *
 * @author nchanwut
 */
@WebServlet(name = "SEC_RegisterController", urlPatterns = {
    "/SEC/Register",
    "/SEC/Register/doRegister"
})
public class SEC_RegisterController extends HttpServlet {

    // <editor-fold defaultstate="collapsed" desc="Init Param">
    private String sampleServletContext;
    @EJB
    private SecLoginBusiness secLoginBusiness;

    @Override
    public void init(ServletConfig servletConfig) throws ServletException {

        super.init(servletConfig);

        // initialize servlet with configuration information
        sampleServletContext = servletConfig.getServletContext().getInitParameter("sampleServletContext");
    }
    // </editor-fold>

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // <editor-fold defaultstate="collapsed" desc="Default Page Param">
        //Request
        request.setCharacterEncoding("UTF-8");  // ensures that user input is interpreted as // 8-bit Unicode (e.g., for Czech characters)
        String userPath = request.getServletPath();
        HttpSession session = request.getSession();
        //Response
        response.setContentType("text/html;charset=utf-8"); //text/json
        Boolean isDispatcher = true; //กำหนดว่า ต้องการให้เปลี่ยนหน้าหรือไม่ ? ต้องการ : ไม่ต้องการ
        // </editor-fold>

        // <editor-fold defaultstate="collapsed" desc="Control Page Redirect & Reset Requset-Attribute">
        if (userPath.equals("/SEC/Register")) {
            // <editor-fold defaultstate="collapsed" desc="URL Param">

            // </editor-fold>

            // <editor-fold defaultstate="collapsed" desc="Attribute Param">

            // </editor-fold>

            // <editor-fold defaultstate="collapsed" desc="Change Page Param">
            userPath = "/SEC/Register";
            isDispatcher = true;
            // </editor-fold>

        }
        // </editor-fold>

        // <editor-fold defaultstate="collapsed" desc="Change Page">
        // use RequestDispatcher to forward request internally
        String url = "/WEB-INF/view" + userPath + ".jsp";
        try {
            if (isDispatcher) {
                request.getRequestDispatcher(url).forward(request, response);
            }
        } catch (Exception ex) {
            //@TODO : Error Code Here
            ex.printStackTrace();
        }
        // </editor-fold>
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // <editor-fold defaultstate="collapsed" desc="Default Page Param">
        //Request
        request.setCharacterEncoding("UTF-8");  // ensures that user input is interpreted as // 8-bit Unicode (e.g., for Czech characters)
        String userPath = request.getServletPath();
        HttpSession session = request.getSession();
        //Response
        response.setContentType("text/json;charset=utf-8");
        PrintWriter out;
        String strJson = "{}";
        Boolean isDispatcher = false; //กำหนดว่า ต้องการให้เปลี่ยนหน้าหรือไม่ ? ต้องการ : ไม่ต้องการ
        // </editor-fold>

        // <editor-fold defaultstate="collapsed" desc="Request Function">
        if (userPath.equals("/SEC/Register/doRegister")) {
            // <editor-fold defaultstate="collapsed" desc="URL Param">
            String txtUsername = (request.getParameter("txtUsername") != null) ? request.getParameter("txtUsername").trim() : "";
            String txtPassword = (request.getParameter("txtPassword") != null) ? request.getParameter("txtPassword").trim() : "";
            String txtConfirmPassword = (request.getParameter("txtPassword") != null) ? request.getParameter("txtConfirmPassword").trim() : "";
            String txtEmail = (request.getParameter("txtEmail") != null) ? request.getParameter("txtEmail").trim() : "";
            String btnSubmitRegister = (request.getParameter("btnSubmitRegister") != null) ? request.getParameter("btnSubmitRegister").trim() : "";

            // </editor-fold>

            // <editor-fold defaultstate="collapsed" desc="Param">
            Boolean blIsSuccess = false;
            // </editor-fold>

            // <editor-fold defaultstate="collapsed" desc="Coding">
            try {
                if (!btnSubmitRegister.isEmpty()) { //Do Regis

                    //@TODO : Validate Here (Server Side function)
                    // <editor-fold defaultstate="collapsed" desc="Validate Data">
                    //@TODO : Validate Password Equal
                    //@TODO : Validate Is Exist Username OR Email? From DB
                    // </editor-fold>

                    // <editor-fold defaultstate="collapsed" desc="Do DB Transaction">
                    blIsSuccess = secLoginBusiness.DoRegister(txtUsername, txtPassword, txtEmail);
                    // </editor-fold>

                    // <editor-fold defaultstate="collapsed" desc="Bind Object To Json Data">
                    out = response.getWriter();
                    strJson = DisplayData();
                    out.println(strJson);
                    // </editor-fold>
                } else {
                    //@TODO : Throw Exception (Invalid Data)
                    out = response.getWriter();
                    out.write(strJson);
                }
            } catch (Exception ex) {
                // <editor-fold defaultstate="collapsed" desc="Popup Message">

                // </editor-fold>
                //@TODO : Implement Error function to show on front
                System.out.println("Error message" + ex.getMessage());
            } finally {
                // <editor-fold defaultstate="collapsed" desc="Clear Value">
                out = null;
                strJson = "";
                // </editor-fold>
                //@TODO : Implement message function to show on front
            }
            // </editor-fold>

            // <editor-fold defaultstate="collapsed" desc="Change Page Param">
            //response.setContentType("text/json;charset=utf-8");
            //userPath = "/SEC/Register";
            isDispatcher = false;
            // </editor-fold>
        }
        // </editor-fold>

        // <editor-fold defaultstate="collapsed" desc="Change Page">
        // use RequestDispatcher to forward request internally
        String url = "/WEB-INF/view" + userPath + ".jsp";
        try {
            if (isDispatcher) {
                request.getRequestDispatcher(url).forward(request, response);
            }
        } catch (Exception ex) {
            //@TODO : Error Code Here
            ex.printStackTrace();
        }
        // </editor-fold>
    }

    // <editor-fold defaultstate="collapsed" desc="Show Message">
    private String DisplayData() {
        // <editor-fold defaultstate="collapsed" desc="Param">
        jQueryFormFormatterUtil objJQueryFormFormatterUtil;
        String strJson = "{}";
        // </editor-fold>

        // <editor-fold defaultstate="collapsed" desc="Mapping Param">
        //Dialog
        List<jQueryFormDialog> mapDialogs = null;
        jQueryFormDialog dialog = null;
        jQueryFormDialogOption dialogOption = null;
        // </editor-fold>

        try {
            // <editor-fold defaultstate="collapsed" desc="Data Bind">

            // <editor-fold defaultstate="collapsed" desc="Bind Dialog Control">
            //Add Dialogs
            mapDialogs = new ArrayList<jQueryFormDialog>();
            dialogOption = new jQueryFormDialogOption(Constant.Msg_SaveCompleted, ConstantjQueryDialogState.Complete);
            dialog = new jQueryFormDialog(strJson, dialogOption);
            mapDialogs.add(dialog);
            // </editor-fold>

            // </editor-fold>

            // <editor-fold defaultstate="collapsed" desc="Build Json String">
            objJQueryFormFormatterUtil = new jQueryFormFormatterUtil();
            //strJson = objJQueryFormFormatterUtil.setDialog(mapDialogs);

            return strJson;
            //ฟังก์ชันเดิมอาจไม่ใช้แล้ว
            //return jQueryFormFormatterUtil.getJSON(mapAttrs, mapRemoveAttr, mapHtml, mapText, mapVal, mapAddClass, mapRemoveClass, mapToggleClass, mapShowHide);
            // </editor-fold>
        } catch (Exception ex) {
            //@TODO : return error by throw exception
            return strJson;
        } finally {
            //@TODO : Clear Value
            // <editor-fold defaultstate="collapsed" desc="Clear Value">
            //srvCurePlan = null;
            strJson = "";
            // </editor-fold>
            //@TODO : Implement message function to show on front
        }
    }
    // </editor-fold>
}
